package cn.easyutil.project.web.handler;

import cn.easyutil.project.base.bean.ResponseBody;
import cn.easyutil.project.base.exception.CommonException;
import cn.easyutil.util.javaUtil.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常统一处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired(required = false)
    private cn.easyutil.project.web.advice.GlobalExceptionAdvice advice;

    /**
     * 统一异常类返回值
     *
     * @param e 异常
     * @return 错误信息JSON字符串
     */
    @ExceptionHandler(Exception.class)
    public Object exception(Exception e) {
        if(!(e instanceof CommonException)){
            LoggerUtil.error(this.getClass(), "", e);
        }
        if(advice == null){
            advice = new DefaultGlobalExceptionAdvice();
        }
        return advice.parseResponseBody(e);
    }
}
